package com.example.watchcat2k.finalproject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.icu.text.SimpleDateFormat;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;
import retrofit2.http.Path;

public class WriteBlogActivity extends AppCompatActivity {
    //图片信息
    private int image_count = 0;
    private String image_base1 = "";
    private String image_base2 = "";
    private String image_base3 = "";
    private String image_base4 = "";
    private String image_base5 = "";
    private String image_base6 = "";

    private String user = "";


    private ImageView back;
    private Button send_blog;
    private EditText blog_content;
    private ImageView image1;
    private ImageView image2;
    private ImageView image3;
    private ImageView image4;
    private ImageView image5;
    private ImageView image6;
    private ImageView delete1;
    private ImageView delete2;
    private ImageView delete3;
    private ImageView delete4;
    private ImageView delete5;
    private ImageView delete6;
    private ConstraintLayout constraintLayout1;
    private ConstraintLayout constraintLayout2;
    private ConstraintLayout constraintLayout3;
    private ConstraintLayout constraintLayout4;
    private ConstraintLayout constraintLayout5;
    private ConstraintLayout constraintLayout6;

    //下面四个按钮，只有pick_image实现了
    private ImageView pick_image;
    private ImageView take_photo;
    private ImageView take_video;
    private ImageView look;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_blog);

        init();

        set_click();
    }

    void init(){
        Intent intent = getIntent();
        user = intent.getStringExtra("user");
        back = (ImageView)findViewById(R.id.imageView_write_blog_back);
        send_blog = (Button) findViewById(R.id.button_write_blog_send);
        blog_content = (EditText)findViewById(R.id.editText_write_blog_centent);

        //下面三个分布对应图像和删除，其中布局=图像+删除
        image1 = (ImageView)findViewById(R.id.imageView_write_blog_image1);
        image2 = (ImageView)findViewById(R.id.imageView_write_blog_image2);
        image3 = (ImageView)findViewById(R.id.imageView_write_blog_image3);
        image4 = (ImageView)findViewById(R.id.imageView_write_blog_image4);
        image5 = (ImageView)findViewById(R.id.imageView_write_blog_image5);
        image6 = (ImageView)findViewById(R.id.imageView_write_blog_image6);

        delete1 = (ImageView)findViewById(R.id.imageView_write_blog_delete1);
        delete2 = (ImageView)findViewById(R.id.imageView_write_blog_delete2);
        delete3 = (ImageView)findViewById(R.id.imageView_write_blog_delete3);
        delete4 = (ImageView)findViewById(R.id.imageView_write_blog_delete4);
        delete5 = (ImageView)findViewById(R.id.imageView_write_blog_delete5);
        delete6 = (ImageView)findViewById(R.id.imageView_write_blog_delete6);

        constraintLayout1 = (ConstraintLayout)findViewById(R.id.constraintLayout4);
        constraintLayout2 = (ConstraintLayout)findViewById(R.id.constraintLayout8);
        constraintLayout3 = (ConstraintLayout)findViewById(R.id.constraintLayout5);
        constraintLayout4 = (ConstraintLayout)findViewById(R.id.constraintLayout10);
        constraintLayout5 = (ConstraintLayout)findViewById(R.id.constraintLayout16);
        constraintLayout6 = (ConstraintLayout)findViewById(R.id.constraintLayout14);

        pick_image = (ImageView)findViewById(R.id.imageView_write_blog_picture);
        take_photo = (ImageView)findViewById(R.id.imageView_write_blog_camera);
        take_video = (ImageView)findViewById(R.id.imageView_write_blog_video);
        look = (ImageView)findViewById(R.id.imageView_write_blog_emoticon);


        constraintLayout1.setVisibility(View.INVISIBLE);
        constraintLayout2.setVisibility(View.INVISIBLE);
        constraintLayout3.setVisibility(View.INVISIBLE);
        constraintLayout4.setVisibility(View.INVISIBLE);
        constraintLayout5.setVisibility(View.INVISIBLE);
        constraintLayout6.setVisibility(View.INVISIBLE);
    }

    void set_click(){

        //下面三个未实现
        take_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(WriteBlogActivity.this, "功能未开放", Toast.LENGTH_SHORT).show();
            }
        });

        look.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(WriteBlogActivity.this, "功能未开放", Toast.LENGTH_SHORT).show();
            }
        });



        take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(image_count == 6){
                    Toast.makeText(WriteBlogActivity.this, "图片已达上限", Toast.LENGTH_SHORT).show();
                }
                else {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系统常量， 启动相机的关键
                    startActivityForResult(openCameraIntent, 1); // 参数常量为自定义的request code, 在取返回结果时有用
                }
            }
        });


        //选择图片,注意判断目前图片数量
        pick_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(image_count == 6){
                    Toast.makeText(WriteBlogActivity.this, "图片已达上限", Toast.LENGTH_SHORT).show();
                }
                else{
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setType("image/*");
                    startActivityForResult(intent, 0);
                }
            }
        });

        //回到主页面
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WriteBlogActivity.this.finish();
            }
        });

        //发送博客
        send_blog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取博客内容
                String content = blog_content.getText().toString();
                if(content.equals("")){
                    Toast.makeText(WriteBlogActivity.this, "发布内容不可为空", Toast.LENGTH_SHORT).show();
                }
                else {
                    ArrayList<String>photos = new ArrayList<>();
                    if(image_count >= 1){
                        photos.add(image_base1);
                    }if(image_count >= 2){
                        photos.add(image_base2);
                    }if(image_count >= 3){
                        photos.add(image_base3);
                    }if(image_count >= 4){
                        photos.add(image_base4);
                    }if(image_count >= 5){
                        photos.add(image_base5);
                    }if(image_count == 6){
                        photos.add(image_base6);
                    }
                    String now_time = getTime();
                    //发送博客数据包
                    ReleaseBlogPacket releaseBlogPacket = new ReleaseBlogPacket(user,content, now_time, photos);
                    //网络请求
                    //网络请求
                    try {
                        OkHttpClient build = new OkHttpClient.Builder()
                                .connectTimeout(2, TimeUnit.SECONDS)
                                .readTimeout(2, TimeUnit.SECONDS)
                                .writeTimeout(2, TimeUnit.SECONDS)
                                .build();

                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl("http://129.204.116.253:8080")

                                .addConverterFactory(GsonConverterFactory.create())

                                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                                // build 即为okhttp声明的变量，下文会讲
                                .client(build)

                                .build();

                        SendBlogService service = retrofit.create(SendBlogService.class);
                        service.postRegister(releaseBlogPacket)
                                .subscribeOn(Schedulers.io())//请求在新的线程中执行
                                .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                                .subscribe(new DisposableObserver<Send_Blog_Confirm_Packet>() {
                                    @Override
                                    public void onNext(Send_Blog_Confirm_Packet send_blog_confirm_packet) {
                                        if(send_blog_confirm_packet.isStatus()){ //发布成功
                                            Toast.makeText(WriteBlogActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                            WriteBlogActivity.this.finish();
                                        }
                                        else {
                                            Toast.makeText(WriteBlogActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        Toast.makeText(WriteBlogActivity.this, "发布失败："+ e.toString(), Toast.LENGTH_SHORT).show();
                                        Log.i("test", "onError: "+e.toString());
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                    }catch (Exception o){
                        Toast.makeText(WriteBlogActivity.this, "抛出异常："+ o.toString(), Toast.LENGTH_SHORT).show();
                        Log.i("test", "onError: "+o.toString());
                    }

                }
            }
        });

        //下面是选择图片之后进行删除
        delete1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (image_count){
                    case 1:
                        constraintLayout1.setVisibility(View.INVISIBLE);
                        image_base1 = "";
                        image_count --;
                        break;
                    case 2:
                        image_base1 = image_base2;
                        image1.setImageBitmap(base64_to_Bitmap(image_base1));
                        image_base2 = "";
                        constraintLayout2.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 3:
                        image_base1 = image_base2;
                        image1.setImageBitmap(base64_to_Bitmap(image_base1));
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = "";
                        constraintLayout3.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 4:
                        image_base1 = image_base2;
                        image1.setImageBitmap(base64_to_Bitmap(image_base1));
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = "";
                        constraintLayout4.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 5:
                        image_base1 = image_base2;
                        image1.setImageBitmap(base64_to_Bitmap(image_base1));
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = "";
                        constraintLayout5.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 6:
                        image_base1 = image_base2;
                        image1.setImageBitmap(base64_to_Bitmap(image_base1));
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = image_base6;
                        image5.setImageBitmap(base64_to_Bitmap(image_base5));
                        constraintLayout6.setVisibility(View.INVISIBLE);
                        image_base6 = "";
                        image_count --;
                        break;
                }
            }
        });

        delete2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (image_count){
                    case 2:
                        constraintLayout2.setVisibility(View.INVISIBLE);
                        image_base2 = "";
                        image_count --;
                        break;
                    case 3:
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = "";
                        constraintLayout3.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 4:
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = image_base4;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base4 = "";
                        constraintLayout4.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 5:
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = "";
                        constraintLayout5.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 6:
                        image_base2 = image_base3;
                        image2.setImageBitmap(base64_to_Bitmap(image_base2));
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = image_base6;
                        image5.setImageBitmap(base64_to_Bitmap(image_base5));
                        image_base6 = "";
                        constraintLayout6.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                }
            }
        });

        delete3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (image_count){
                    case 3:
                        constraintLayout3.setVisibility(View.INVISIBLE);
                        image_base3 = "";
                        image_count --;
                        break;
                    case 4:
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = "";
                        constraintLayout4.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 5:
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = "";
                        constraintLayout5.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 6:
                        image_base3 = image_base4;
                        image3.setImageBitmap(base64_to_Bitmap(image_base3));
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = image_base6;
                        image5.setImageBitmap(base64_to_Bitmap(image_base5));
                        image_base6 = "";
                        constraintLayout6.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                }
            }
        });

        delete4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (image_count){
                    case 4:
                        constraintLayout4.setVisibility(View.INVISIBLE);
                        image_base4 = "";
                        image_count --;
                        break;
                    case 5:
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = "";
                        constraintLayout5.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                    case 6:
                        image_base4 = image_base5;
                        image4.setImageBitmap(base64_to_Bitmap(image_base4));
                        image_base5 = image_base6;
                        image5.setImageBitmap(base64_to_Bitmap(image_base5));
                        image_base6 = "";
                        constraintLayout6.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                }
            }
        });

        delete5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (image_count){
                    case 5:
                        constraintLayout5.setVisibility(View.INVISIBLE);
                        image_base5 = "";
                        image_count --;
                        break;
                    case 6:
                        image_base5 = image_base6;
                        image5.setImageBitmap(base64_to_Bitmap(image_base5));
                        image_base6 = "";
                        constraintLayout6.setVisibility(View.INVISIBLE);
                        image_count --;
                        break;
                }
            }
        });

        delete6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                constraintLayout6.setVisibility(View.INVISIBLE);
                image_base6 = "";
                image_count --;
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if ( resultCode == RESULT_OK) {
                    //相机自动压缩了，不需要我们进行压缩
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    bm = Bitmap.createScaledBitmap(bm, 400, 400, true);
                    switch (image_count){
                        case 0:
                            constraintLayout1.setVisibility(View.VISIBLE);
                            image1.setImageBitmap(bm);
                            image_base1 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 1:
                            constraintLayout2.setVisibility(View.VISIBLE);
                            image2.setImageBitmap(bm);
                            image_base2 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 2:
                            constraintLayout3.setVisibility(View.VISIBLE);
                            image3.setImageBitmap(bm);
                            image_base3 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 3:
                            constraintLayout4.setVisibility(View.VISIBLE);
                            image4.setImageBitmap(bm);
                            image_base4 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 4:
                            constraintLayout5.setVisibility(View.VISIBLE);
                            image5.setImageBitmap(bm);
                            image_base5 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 5:
                            constraintLayout6.setVisibility(View.VISIBLE);
                            image6.setImageBitmap(bm);
                            image_base6 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        default:
                            break;
                    }

                }
                break;
            case 0:
                if(data != null){
                    Uri uri = data.getData();
                    Bitmap bm = get_image_Bitmap(uri);
                    switch (image_count){
                        case 0:
                            constraintLayout1.setVisibility(View.VISIBLE);
                            image1.setImageBitmap(bm);
                            image_base1 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 1:
                            constraintLayout2.setVisibility(View.VISIBLE);
                            image2.setImageBitmap(bm);
                            image_base2 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 2:
                            constraintLayout3.setVisibility(View.VISIBLE);
                            image3.setImageBitmap(bm);
                            image_base3 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 3:
                            constraintLayout4.setVisibility(View.VISIBLE);
                            image4.setImageBitmap(bm);
                            image_base4 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 4:
                            constraintLayout5.setVisibility(View.VISIBLE);
                            image5.setImageBitmap(bm);
                            image_base5 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        case 5:
                            constraintLayout6.setVisibility(View.VISIBLE);
                            image6.setImageBitmap(bm);
                            image_base6 = Bitmap_to_base64(bm);
                            image_count++;
                            break;
                        default:
                            break;
                    }
                }
                else{
                    Toast.makeText(WriteBlogActivity.this,"取消图片选择",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private Bitmap get_image_Bitmap(Uri uri){

        try{
            // 读取本地图库uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
            bitmap = Bitmap.createScaledBitmap(bitmap, 400, 400, true);
            //图库的图片可能太大，压缩
            ByteArrayOutputStream a = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, a);
            if(a.toByteArray().length > 20000){
                a.reset();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 50, a);
            }
            return bitmap;
        }
        catch (Exception e) {
            Toast.makeText(WriteBlogActivity.this,"图片选取失败",Toast.LENGTH_SHORT).show();
            return null;
        }
    }

    private String Bitmap_to_base64(Bitmap bitmap){
        ByteArrayOutputStream a = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, a);
        String result = Base64.encodeToString(a.toByteArray(), Base64.DEFAULT);
        return result;
    }

    private Bitmap base64_to_Bitmap(String icon){
        byte[] bytes = Base64.decode(icon, Base64.DEFAULT);
        Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return bm;
    }

    private String getTime(){
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        return year + "-" + month + "-" + day + " " + hour + ":" + minute;
        /*
        SimpleDateFormat formatter   =   new SimpleDateFormat("YY-MM-DD HH:MM");
        Date curDate =  new Date(System.currentTimeMillis());
        return formatter.format(curDate);
        */
    }

    public interface SendBlogService{
        @POST("/blog/releaseBlog")
        Observable<Send_Blog_Confirm_Packet> postRegister(@Body ReleaseBlogPacket releaseBlogPacket);
    }


}
